package com.ddxz.demo.clickhouse.service.impl;

import com.ddxz.demo.clickhouse.entity.ClickHouseEntity;
import com.ddxz.demo.clickhouse.mapper.ClickHouseMapper;
import com.ddxz.demo.clickhouse.service.ClickHouseService;
import com.ddxz.tool.web.dto.DdxzResponse;
import com.ddxz.tool.web.dto.PageRequest;
import com.ddxz.tool.web.dto.PageResponse;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * description
 *
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2021/3/22
 */

@Service
public class ClickHouseServiceImpl implements ClickHouseService {
    @Override
    public DdxzResponse getPageList(PageRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        Page<Map<String, Object>> page = mapper.getPageList();
        PageResponse<Map<String, Object>> response = new PageResponse<>(page.getResult().size());
        response.setTotalElements(page.getTotal());
        response.setTotalPage(page.getPages());
        response.setContent(page.getResult());
        return DdxzResponse.correct(response);
    }

    @Override
    public DdxzResponse addDataTest(Long second) {
        // 国际漫游 - 异常网元基线数据计算
        Integer num = mapper.insertCountryRoamElement(second);
        return DdxzResponse.correct(num);
    }

    @Override
    public DdxzResponse update(ClickHouseEntity entity) {
        ClickHouseEntity oldVal = mapper.getEntityByIdAndVersion(entity.getId(), entity.getVersion());
        oldVal.setSign((short) -1);
        ClickHouseEntity newVal = new ClickHouseEntity();
        if(oldVal.getAge() == null) {
            newVal.setAge(1);
        } else {
            newVal.setAge(oldVal.getAge() + 1);
        }
        newVal.setName(oldVal.getName());
        newVal.setId(oldVal.getId());
        newVal.setSign((short) 1);
        newVal.setVersion(oldVal.getVersion()+1);

        mapper.updateVersionMergeTree(oldVal, newVal);
        return null;
    }

    @Override
    public DdxzResponse generateDate(String tableName, String startDate, String stopDate) {
        return null;
    }

    private final ClickHouseMapper mapper;

    public ClickHouseServiceImpl(ClickHouseMapper mapper) {
        this.mapper = mapper;
    }
}
